package cn.reinforce.util.dsm;

import cn.reinforce.util.dsm.model.ApiInfo;
import cn.reinforce.util.dsm.model.FileInfo;
import cn.reinforce.util.dsm.model.FileResult;
import cn.reinforce.util.dsm.model.Result;
import cn.reinforce.util.dsm.model.SearchStart;
import cn.reinforce.util.http.HttpClientUtil;
import cn.reinforce.util.http.model.HttpResult;
import cn.reinforce.util.image.ImageUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author 幻幻Fate
 * @date 2021/10/19
 */
public class FileStationUtil {

    private FileStationUtil() {
    }

    public static List<FileInfo> getFileList(String folder){
        String data = AuthUtil.requestData("SYNO.FileStation.List", "list", "&folder_path=" + folder, null);
        Gson gson = new GsonBuilder().create();
        FileResult result = gson.fromJson(data, FileResult.class);
        return result.getFiles();
    }

    public static String startSearch(String folder, boolean recursive, String pattern){
        String data = AuthUtil.requestData("SYNO.FileStation.Search", "start", "&folder_path=" + folder + "&recursive=" + recursive + "&pattern=" + pattern, null);
        Gson gson = new GsonBuilder().create();
        SearchStart result = gson.fromJson(data, SearchStart.class);
        return result.getTaskId();
    }

    public static FileResult listSearch(String taskId, Integer pageNum, Integer pageSize){
        String data = AuthUtil.requestData("SYNO.FileStation.Search", "list", "&taskid=" + taskId + "&offset=" + (pageNum - 1) * pageSize + "&limit=" + pageSize, null);
        Gson gson = new GsonBuilder().create();
        FileResult result = gson.fromJson(data, FileResult.class);
        return result;
    }

    public static void getFile(String filename, String path, String mode, String localPath) throws UnsupportedEncodingException {
        Dsm dsm = Dsm.INSTANCE;
        String apiName = "SYNO.FileStation.Download";
        String apiPath = dsm.getApis().get(apiName).getPath();
        String url = dsm.getBaseUrl() + apiPath + "?api=" + apiName + "&version=" + dsm.getApis().get(apiName).getMaxVersion() + "&method=download" + "&path=" + URLEncoder.encode(path, "UTF-8") + "&mode=" + mode;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String fileType = url.substring(url.lastIndexOf(".") + 1);
        File dir = new File(localPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File storeFile = new File(localPath + File.separator + filename);
        FileOutputStream output = null;
        try {
            HttpGet get = new HttpGet(url);
            get.addHeader("Content-Type", "text/html;charset=UTF-8");
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36");
            get.addHeader("cookie", "id=" + dsm.getSid() + ";");
            CloseableHttpResponse response = httpclient.execute(get);
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                InputStream input = responseEntity.getContent();
                output = new FileOutputStream(storeFile);
                IOUtils.copy(input, output);
                output.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
